package admin

import (
	"context"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/datatypes"
)

type PermissionSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPermissionSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PermissionSaveLogic {
	return &PermissionSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PermissionSaveLogic) PermissionSave(req *types.PermissionSaveReq) (resp string, err error) {
	data := &models.Permission{}

	copier.Copy(data, req)

	if req.Params != nil {
		data.Params = datatypes.JSON(utils.StructToJson(req.Params))
	}

	if req.Id == 0 {
		// 创建新权限
		err = utils.InsertData(data)
	} else {
		// 更新现有权限
		err = utils.UpdateById(req.Id, data)
	}

	if err != nil {
		return "", err
	}

	return "操作成功", nil
}
